package com.lh_travel.lohas.adapter;

import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;
import com.lh_travel.lohas.interfaces.PageIndex;
import java.util.LinkedList;
import java.util.List;

public abstract class ConverPageAdapter<T> extends PagerAdapter{

    LinkedList<View> viewLinkedList = new LinkedList<>();

    private Context mContext;
    private int ResID;
    private List<T> datas;
    private PageIndex pageIndex;

    public ConverPageAdapter(Context mContext, int resID, List<T> datas, PageIndex pageIndex) {
        this.mContext = mContext;
        ResID = resID;
        this.datas = datas;
        this.pageIndex = pageIndex;
    }

    @Override
    public int getCount() {
        return datas.size();
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {

        return view == object;
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {

        View itemView;
        if (viewLinkedList.size() > 0) {
            itemView = viewLinkedList.getFirst();
            viewLinkedList.removeFirst();

        } else {
            itemView = View.inflate(mContext, ResID, null);
        }

        itemView.setTag(position);

        convert(itemView, datas.get(position), position);

        container.addView(itemView);

        return itemView;

    }

    @Override
    public int getItemPosition(Object object) {

        View view = (View) object;

        if (pageIndex.getIndex() == (Integer) view.getTag()){

            return POSITION_NONE;

        }else {

            return  POSITION_UNCHANGED;
        }

    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((View) object);
        if (object != null) {
            viewLinkedList.addLast((View) object);
        }

    }

    public abstract void convert(View view, T item, int position);
}
